package com.mxpio.erp.technology.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mxpio.erp.common.technology.entity.ItemGroup;
import com.mxpio.erp.common.technology.service.ItemGroupService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.query.Criteria;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "ItemGroupService", description = "物料组接口")
@RestController
@RequestMapping("/erp/common/item/group/")
public class ItemGroupController {
	
	@Autowired
	private ItemGroupService itemGroupsSerivce;

	@GetMapping("tree")
	@Operation(summary = "物料组树", description = "获取物料组", method = "GET")
	public Result<List<ItemGroup>> list(Criteria criteria) throws UnsupportedEncodingException {
		List<ItemGroup> itemGroups = itemGroupsSerivce.tree(ItemGroup.class, criteria);
		return Result.OK(itemGroups);
	}
	
	@GetMapping("list/{groupCode}")
	@Operation(summary = "根据groupCode获取物料组", description = "根据groupCode获取物料组", method = "GET")
	public Result<ItemGroup> getById(@PathVariable(name = "groupCode", required = true) String groupCode) {
		ItemGroup itemGroup = itemGroupsSerivce.getById(ItemGroup.class, groupCode);
		return Result.OK(itemGroup);
	}
	
	@PostMapping("add")
	@Operation(summary = "新增物料组", description = "新增物料组", method = "POST")
	public Result<ItemGroup> add(@RequestBody ItemGroup itemGroup) {
		itemGroupsSerivce.save(itemGroup);
		return Result.OK(itemGroup);
	}
	
	@PutMapping("edit")
	@Operation(summary = "编辑物料组", description = "编辑物料组（全量）", method = "PUT")
	public Result<ItemGroup> edit(@RequestBody ItemGroup itemGroup) {
		itemGroupsSerivce.update(itemGroup);
		return Result.OK(itemGroup);
	}
	
	@DeleteMapping("remove/{groupCode}")
	@Operation(summary = "删除物料组", description = "删除物料组", method = "DELETE")
	public Result<ItemGroup> remove(@PathVariable(name = "groupCode", required = true) String groupCode) {
		String ids[] = groupCode.split(",");
		for(String key : ids){
			itemGroupsSerivce.delete(ItemGroup.class, key);
		}
		return Result.OK();
	}
	
}
